import config from '@/config'
import storage from '@/utils/storage'
import {
	decryptedDes
} from "@/utils/crypto/encrypt-des";
import constant from '@/utils/constant'
import {
	login,
	logout,
	getInfo,
	getPublicKey,
	getPublicKeyC,
	findMenuTree
} from '@/api/login'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'
import {
	isNull
} from '@/utils/validate.js'

const baseUrl = config.baseUrl
const notDisableMenu = [
	'我的客户',
	'储备客户池',
	'测评中心',
	'会员信息',
	'会员合同',
	'线下班级',
	'签到管理',
	'我的学生',
	'训练计划',
	'课程管理',
	'报名续费记录',
	'资源中心',
]
const user = {
	getState() {

	},
	state: function() {
		let asdfasd = {}



		for (let key in constant) {

			let asdf = asdfasd[key] = storage.get(constant[key])
			if (isNull(asdf)) {
				asdfasd[key] = asdf
			}

			if (key == 'token') {
				asdfasd[key] = getToken()
			}

		}

		return asdfasd
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_NAME: (state, name) => {
			state.name = name
			storage.set(constant.name, name)
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
			storage.set(constant.avatar, avatar)
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
			storage.set(constant.roles, roles)
		},
		SET_PERMISSIONS: (state, permissions) => {
			state.permissions = permissions
			storage.set(constant.permissions, permissions)
		},
		SET_USER: (state, user) => {
			state.user = user
			storage.set(constant.user, user)
		},
		SET_MENU: (state, menu) => {
			state.menu = menu
			storage.set(constant.menu, menu)
		},
		SET_INDEX_TOP_BAR: (state, indexTopBar) => {
			state.indexTopBar = indexTopBar
			storage.set(constant.indexTopBar, indexTopBar)
		},
		SET_PERMS: (state, perms) => {
			state.perms = perms
			storage.set(constant.perms, perms)
		},


	},

	actions: {

		// 登录
		async Login({
			commit
		}, userInfo) {
			const principal = userInfo.principal.trim()
			const password = userInfo.password
			const code = userInfo.code
			const uuid = userInfo.uuid

			let data1 = {
				principal,
				password,
				uuid,
				verificationCode: "",
				loginFrom: "0"
			}
			let publicKey = await getPublicKeyC();
			const {
				data
			} = await login(data1);


			let tmpData = data1;
			if (true) {
				// 获得公钥

				console.log(data + "-----------------" + publicKey);
				// 解密数据
				let decryptedStr = decryptedDes(data, publicKey);
				// 转换为Json
				tmpData = JSON.parse(decryptedStr);
				console.log(tmpData.accessToken);
				setToken(tmpData.accessToken)
				commit('SET_TOKEN', tmpData.accessToken)


			}
			return
		},

		WeChatLogin({
			commit,
			state
		}, data) {
			setToken(data.token)
			commit('SET_TOKEN', data.token)
		},

		// 获取用户信息
		GetInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {

					const user = res.data
					const avatar = (user == null || user.avatar == "" || user.avatar == null) ?
						require("@/static/images/profile.jpg") : user.avatar
					const username = (user == null || user.username == "" || user.username ==
						null) ? "" : user.username
					if (user.roles && user.roles.length > 0) {
						commit('SET_ROLES', user.roles)
						commit('SET_PERMISSIONS', user.permissions)
					} else {
						commit('SET_ROLES', ['ROLE_DEFAULT'])
					}
					commit('SET_PERMS', user.perms)

					// constant.initIndexTopBar().then(rrr => {

					// 	commit('SET_INDEX_TOP_BAR', rrr)

					// })
					commit('SET_USER', user)
					commit('SET_NAME', username)
					commit('SET_AVATAR', avatar)
					resolve(user)

				}).catch(error => {
					reject(error)
				})
			})
		},

		// 设置首页的 INDEX_TOP_BAR
		commitSetSET_INDEX_TOP_BAR({
			commit
		}, data) {
			commit('SET_INDEX_TOP_BAR', data)
		},

		/**
		 * 获取菜单信息
		 */
		getMenu({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				findMenuTree().then(res => {
					let data = res.data

					// 从后向前遍历并删除元素
					for (let i = data.length - 1; i >= 0; i--) {
						for (let i2 = data[i].children.length - 1; i2 >= 0; i2--) {

							if (!notDisableMenu.includes(data[i].children[i2].meta.title)) {
								data[i].children.splice(i2, 1);
							}
						}
					}


					for (let s of data) {
						for (let s2 of s.children) {
							let url = "/pages/" + s2.path + "/" + s2.path
							url = url.replace(/\/\//g, "/");
							// 假设你想检查的页面路径为 '/pages/some/path'
							s2.isok = false

							uni.getFileInfo({
								filePath: url,
								success() {
									s2.isok = true
								},
								fail() {
									s2.isok = false
								}
							})

						}

					}

					commit('SET_MENU', data)
					commit('SET_INDEX_TOP_BAR', data)
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 退出系统
		LogOut({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				logout(state.token).then(() => {

				}).catch(error => {
					reject(error)
				}).finally(res => {

					commit('SET_TOKEN', '')
					commit('SET_ROLES', [])
					commit('SET_PERMISSIONS', [])
					removeToken()
					storage.clean()
					resolve()
				})
			})
		}
	}
}

export default user